package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.widget.EditText;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.PublishImageListAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.internal.component.DaggerPublishCosComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.GetUploadImageTokenModule;
import com.zw.yzk.kabu.internal.module.PublishCosModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.model.PublishImageModel;
import com.zw.yzk.kabu.presenter.PublishCosPresenter;
import com.zw.yzk.kabu.utils.ImageUtils;
import com.zw.yzk.kabu.utils.StringUtils;
import com.zw.yzk.kabu.view.view.PublishCosView;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by zhanwei on 2017/1/2.
 */

public class PublishCosplayActivity extends BaseActivity implements PublishCosView {

    @Bind(R.id.cos_remark)
    public EditText remark;
    @Bind(R.id.cos_images)
    public RecyclerView imageList;
    public PublishImageListAdapter adapter;

    @Inject
    PublishCosPresenter presenter;
    private String uploadImageToken;

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish_cosplay;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {

    }

    @Override
    public void initComponent() {
        DaggerPublishCosComponent
                .builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .publishCosModule(new PublishCosModule())
                .getUploadImageTokenModule(new GetUploadImageTokenModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getUploadImageToken();
        initRecyclerView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.destroy();
    }

    @OnClick(R.id.cancel)
    public void cancel() {
        finish();
    }

    @OnClick(R.id.send)
    public void send() {
        String remarkStr = remark.getText().toString();
        if (TextUtils.isEmpty(remarkStr)) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.please_enter_image_remark));
        } else if (adapter.getImageList().isEmpty()) {
            ToastManager.getInstance().showToast(this, getResources().getString(R.string.one_image_at_least));
        } else {
            LoadingDialogManager.getInstance().showLoadingDialog(this);
            publish("深圳", adapter.getImageList(), remark.getText().toString());
        }

    }

    private String tmp;

    @OnTextChanged(value = R.id.cos_remark, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)
    void beforeTextChanged(CharSequence s, int start, int count, int after) {
        tmp = s.toString();
    }

    @OnTextChanged(value = R.id.cos_remark, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChanged(CharSequence s, int start, int before, int count) {
        if (before == 1) {
            //删除操作
            String space = tmp.substring(start);
            String current = s.toString();
            if (" ".equals(space) && !current.endsWith(" ") && current.contains("@")) {
                remark.setText(current.substring(0, current.lastIndexOf("@")));
            }
        }
        boolean hasTopic = !StringUtils.divideString(s.toString().replace(tmp, "#"), StringUtils.DIVIDE_STRING_PATTERN1).isEmpty();
        if (s.toString().endsWith("#") && before == 0 && !hasTopic) {
            startActivityForResult(new Intent(this, SearchOrCreateTopicActivity.class), ActivityConstant.SELECT_PUBLISH_TOPIC);
        } else if (s.toString().endsWith("@")) {
            startActivityForResult(new Intent(this, AtUserActivity.class), ActivityConstant.SELECT_AT_USER_TOPIC);
        }
        remark.setSelection(remark.getText().length());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ActivityConstant.OPEN_EDIT_COS_IMAGE_CODE:
                    if (data == null) {
                        return;
                    }
                    List<PublishImageModel> modelList = data.getParcelableArrayListExtra(ActivityConstant.EDIT_COS_IMAGE_COMPLETE);
                    adapter.refresh(modelList);
                    break;
                case ActivityConstant.SELECT_PUBLISH_TOPIC:
                    String topic = data.getStringExtra(ActivityConstant.PUBLISH_TOPIC);
//                    String s = remark.getText().toString() + topic.substring(1);
//                    remark.setText(StringUtils.colorTextWithPattern(s, StringUtils.DIVIDE_STRING_PATTERN1, ContextCompat.getColor(this, R.color.gold)));
                    setRemarkContent(topic.substring(1));
                    break;
                case ActivityConstant.SELECT_AT_USER_TOPIC:
                    String user = data.getStringExtra(ActivityConstant.AT_USER) + " ";
//                    String ss = remark.getText().toString() + user;
//                    remark.setText(ss);
                    setRemarkContent(user);
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void publishSuccess() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setResult(ActivityConstant.PUBLISH_COS_SUCCESS, new Intent());
                finish();
            }
        }, 500);
    }

    @Override
    public void getUploadImageTokenSuccess(String token) {
        this.uploadImageToken = token;
    }

    /**
     * 设置remark
     *
     * @param extras
     */
    private void setRemarkContent(String extras) {
        String s = remark.getText().toString() + extras;
        SpannableString topic = StringUtils.colorTextWithPattern(s, StringUtils.DIVIDE_STRING_PATTERN1, ContextCompat.getColor(this, R.color.gold));
        SpannableString at = StringUtils.colorTextWithPattern(topic, StringUtils.DIVIDE_STRING_PATTERN2, ContextCompat.getColor(this, R.color.gold));
        remark.setText(at);
    }

    /**
     * 初始化recyclerview
     */
    private void initRecyclerView() {
        //设置为网格显示
        imageList.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        //设置默认动画
        imageList.setItemAnimator(new DefaultItemAnimator());
        adapter = new PublishImageListAdapter(null, 9);
        //设置点击+号选择图片
        adapter.setOnAddImageClickedListener(new PublishImageListAdapter.OnImageClickedListener() {
            @Override
            public void onAddImageClicked() {
                selectImage();
            }

            @Override
            public void onImageContentClicked() {
                Intent intent = new Intent(PublishCosplayActivity.this, EditCosImageActivity.class);
                intent.putParcelableArrayListExtra(ActivityConstant.EDIT_COS_IMAGE, adapter.getImageList());
                startActivityForResult(intent, ActivityConstant.OPEN_EDIT_COS_IMAGE_CODE);
            }
        });
        imageList.setAdapter(adapter);
    }

    /**
     * 打开图片选择器
     */
    public void selectImage() {
        int maxSize = adapter == null || adapter.getItemCount() == 1 ? 9 : 10 - adapter.getItemCount();

        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(false)
                .setEnableEdit(false)
                .setEnableCrop(false)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .setForceCrop(false)
                .setMutiSelectMaxSize(maxSize)
                .build();
        GalleryFinal.openGalleryMuti(ActivityConstant.OPEN_GALLERY, functionConfig, new GalleryFinal.OnHandlerResultCallback() {
            @Override
            public void onHandlerSuccess(int requestCode, List<PhotoInfo> resultList) {
                if (ActivityConstant.OPEN_GALLERY == requestCode) {
                    if (resultList.size() <= 0) {
                        ToastManager.getInstance().showToast(PublishCosplayActivity.this, getResources().getString(R.string.read_file_error));
                    } else {
                        //不做压缩
//                        String url = ImageUtils.compress(PublishCosplayActivity.this, new File(resultList.get(0).getPhotoPath()));
                        List<PublishImageModel> list = new ArrayList<>();
                        for (PhotoInfo info : resultList) {
                            PublishImageModel model = new PublishImageModel();
                            model.setContentPath(info.getPhotoPath());
                            model.setRemark(null);

                            list.add(model);
                        }
                        adapter.add(list);
                    }
                }
            }

            @Override
            public void onHandlerFailure(int requestCode, String errorMsg) {
                ToastManager.getInstance().showToast(PublishCosplayActivity.this, errorMsg + "(" + requestCode + ")");
            }
        });
    }

    /**
     * 获取七牛图片上传token
     */
    public void getUploadImageToken() {
        presenter.getUploadImageToken();
    }

    /**
     * 上传图片到七牛
     *
     * @param address    地址
     * @param modelList  图片列表
     * @param topContent 说明
     */
    public void publish(String address, List<PublishImageModel> modelList, String topContent) {
        presenter.publish(address, modelList, topContent, uploadImageToken);
    }
}
